
import 'dart:async';

import 'package:flutter/services.dart';

typedef void EventCallback(args,args2,args3);

class FlutterDesktopAlert {
  static const MethodChannel _channel = MethodChannel('flutter_desktop_alert');

  static const EventChannel? _eventChannel = EventChannel("flutter_desktop_alert/event");

  static EventCallback? callBack;

  StreamSubscription<dynamic>? _streamSubscription;

  // 方法1：初始化构造方法设置监听内容(统一分发)
  FlutterDesktopAlert(){
    _streamSubscription =  _eventChannel?.receiveBroadcastStream().listen((event) {
      final Map<dynamic,dynamic> map = event;
      print("map = $map");
      String? key = map["event"];
      String? shareCount = map["shareCount"];
      String? money = map["money"];
      print("handle on ---$key---$money---$shareCount");
      if(map["event"] == "initCall"){
        callBack!(key,shareCount,money);
      }
      else if(map["event"] == "updateCall") {
        callBack!(key,shareCount,money);
      }
    },onError: errorEventListen,onDone:doneEventListen,) as StreamSubscription;

    // WidgetsBinding.instance!.addObserver(this);
  }

  errorEventListen(Object obj) {
    final Object e = obj;
    print("错误打印为------$obj");
    throw e;
  }

  doneEventListen() {
    print("flutter响应完成------");
  }

  static void listener(EventCallback tempCallback) {
    callBack = tempCallback;
  }

  static Future<String?> get platformVersion async {
    final String? version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  // 创建桌面小插件
  static Future<String?> creatDesktopWidget(String shareCount,String money) async {
    final String? content = await _channel.invokeMethod('creatDesktop',{"money":money,"shareCount":shareCount});
    return content;
  }

  // 更新桌面小插件
  static Future<String?> updateDesktopWidget(String shareCount,String money) async {
    final String? content = await _channel.invokeMethod('updateDesktopWidget',{"money":money,"shareCount":shareCount});
    return content;
  }
}
